/*******************************************************************************
 * Copyright (c) 2013 Zero Square LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Zero Square LLC. Version 1
 * which accompanies this distribution
 ******************************************************************************/
package com.zsqr.dashboard.dao;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import com.zsqr.dashboard.commons.dao.GenericJpaDao;
import com.zsqr.dashboard.domain.UserEntity;


/**
 * Data Access Object JPA implementation to work with User Entity DB Operation
 * @author Saurabh
 *
 */
public class UserJpaDao extends GenericJpaDao<UserEntity,Long> implements UserDao {

	public UserJpaDao() {
		super(UserEntity.class);
		}

	/**
	 * Queries Database for user name availability
	 * @param userName
	 * @return true if requested user name available
	 */
	public boolean checkAvailable(String userName) {
		//put null check for parameter
		Assert.notNull(userName);
		
		//Now we will create query
		Query query =getEntityManager().createQuery("select count(*) from " + getPersistenceClass().getSimpleName()
				+" u where u.userName = :userName").setParameter("userName",userName);
		
		//Capture the result
		Long count = (Long) query.getSingleResult();
		
		//here if query will get zero row means user is available and it will return true
		return count<1;
	}

	/**
	 * Queries for user name
	 * @param userName
	 * @return UserEntity
	 */
	public UserEntity loadUserByUserName(String userName) {
		//null check for username
		Assert.notNull(userName);
		
		UserEntity user = null;
		try{
		//run query to get whole entity and load object in memory
		Query query = getEntityManager().createQuery("select u from " + getPersistenceClass().getSimpleName()
				
				+ " u where u.userName=:userName").setParameter("userName", userName);
		
		//catch object in UserEntity
		user = (UserEntity)query.getSingleResult();
		}catch(NoResultException e){
			//Do nothing as in case of exception user will retrun null
			return null;
		}		
		return user;
	}
	
	
	
	public boolean createUser(UserEntity userEntity)
	{
		
		
		//UserEntity user = null;
		try{
		//run query to get whole entity and load object in memory
		Query query = getEntityManager().createQuery("insert into " + getPersistenceClass().getSimpleName()
				+ " u values").setParameter("u", userEntity);
		
		//catch object in UserEntity
		if(query.executeUpdate() == 0)
			return false;
		
		}catch(NoResultException e){
			//Do nothing as in case of exception user will retrun null
			return false;
		}		
		return true;
	}
}
	
	

